import asyncio
import websockets
import json
import datetime

async def control_asr(websocket):
    """Send ASR control messages based on even/odd minutes."""
    last_minute = -1  # Initialize with an impossible value to ensure first check works
    
    while True:
        current_time = datetime.datetime.now()
        current_minute = current_time.minute
        
        # Only send a message if we've moved to a new minute
        if current_minute != last_minute:
            # Even minutes (0, 2, 4, etc.): Turn on ASR
            if current_minute % 2 == 0:
                message = json.dumps({"voice": "on"})
                await websocket.send(message)
                print(f"[{current_time.strftime('%H:%M:%S')}] Sent: ASR ON")
            # Odd minutes (1, 3, 5, etc.): Turn off ASR
            else:
                message = json.dumps({"voice": "off"})
                await websocket.send(message)
                print(f"[{current_time.strftime('%H:%M:%S')}] Sent: ASR OFF")
            
            last_minute = current_minute
        
        # Check every second to avoid missing a minute change
        await asyncio.sleep(1)

async def receive_messages(websocket):
    """Receive and display messages from the server."""
    while True:
        try:
            message = await websocket.recv()
            data = json.loads(message)
            print(f"Received: {data}")
        except websockets.exceptions.ConnectionClosed:
            print("Connection closed")
            break

async def main():
    uri = "ws://localhost:8765"
    try:
        async with websockets.connect(uri) as websocket:
            print("Connected to WebSocket server")
            
            # Create tasks for sending control messages and receiving responses
            control_task = asyncio.create_task(control_asr(websocket))
            receive_task = asyncio.create_task(receive_messages(websocket))
            
            # Wait for both tasks to complete (or error)
            await asyncio.gather(control_task, receive_task)
    except Exception as e:
        print(f"Connection error: {e}")

if __name__ == "__main__":
    asyncio.run(main())